package com.rambler.fileupload.config;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.Bean;

/**
 * @author suhao
 */
@Slf4j
@Configuration
public class OSSConfig {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.expire-time}")
    private long expireTime = 3600;

    @Value("${oss.region}")
    private String region;

    private OSS instance;

    @Bean
    @Scope("singleton")
    public OSS ossClient() throws ClientException {

        if (!isEnvPathConfigurationAvailable()) {
            log.error("读取OSS环境变量失败");
            return null;
        }

        // 从环境变量获取访问凭证, 需提前配置 OSS_ACCESS_KEY_ID 和 OSS_ACCESS_KEY_SECRET
        // 设置后, idea需要重启才生效
        ClientBuilderConfiguration config = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        config.setSignatureVersion(SignVersion.V4);

        this.instance = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider())
                .clientConfiguration(config)
                .region(region)
                .build();
        return this.instance;
    }

    @PreDestroy
    public void onDestroy() {
        if (this.instance != null) {
            this.instance.shutdown();
        }
    }

    /**
     * 检查环境变量是否可用
     *
     * @return true/false
     */
    public static boolean isEnvPathConfigurationAvailable() {
        return System.getenv("OSS_ACCESS_KEY_ID") != null && System.getenv("OSS_ACCESS_KEY_SECRET") != null;
    }
}
